from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .serializers import SettlementSerializer, OrderCreateSerializer
from rest_framework.generics import CreateAPIView


class SettlementView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        # 1.从redis中读取选中商品、商品及数量
        redis_cli = get_redis_connection('cart')
        sku_ids = redis_cli.smembers('cart_selected%d' % user.id)
        sku_ids = [int(sku_id) for sku_id in sku_ids]
        sku_dict = redis_cli.hgetall('cart%d' % user.id)
        sku_dict = {int(sku_id): int(count) for sku_id, count in sku_dict.items()}

        # 2.查询商品对象
        skus = SKU.objects.filter(pk__in=sku_ids)

        # 3.遍历，添加数量属性
        for sku in skus:
            sku.count = sku_dict[sku.id]

        # 4.序列化输出
        serializer = SettlementSerializer({
            'freight': 10.00,
            'skus': skus
        })

        return Response(serializer.data)


class OrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCreateSerializer
